<template>
	<view class="css-page page-bg">
		<uv-navbar title="新用户注册" safeAreaInsetTop fixed placeholder leftIcon="account" :autoBack="false"></uv-navbar>

		<view class="css-flex-y css-justify-center css-margin-top-xl css-margin-lr" style="margin-top: 60%;">
			<!-- #ifdef H5 -->
			<uv-form :model="loginForm" :rules="loginRules" ref="loginForm" labelAlign="right" labelWidth="80" >

				<uv-form-item label="用户名:" borderBottom prop="username">
					<uv-input border="none" v-model="loginForm.username" placeholder="请输入用户名或手机号" />
				</uv-form-item>
				<uv-form-item label="密码:" borderBottom prop="password">
					<uv-input border="none" type="password" v-model="loginForm.password" placeholder="请输入密码" />
				</uv-form-item>
				<uv-form-item label="确认密码:" borderBottom prop="confirm_password">
					<uv-input border="none" type="password" v-model="loginForm.confirm_password" placeholder="请输入密码" />
				</uv-form-item>
				<uv-form-item label="验证码" prop="captcha" borderBottom labelWidth="80" width="60%">
					<uv-input v-model="loginForm.captcha" border="none" placeholder="请填写验证码">
						<template v-slot:suffix class="" style="width: 20%;height: 30%;">
							<uv-image @click="getImgCode" :src="imgPic" width="100px"  height="40px" > </uv-image>
							<!-- <uv-image src="http://127.0.0.1:8000/dev-api/captcha/default/7a7eca1f-0e0c-c48b-516e-095a1ac6d9a8" width="100px"  height="40px" > </uv-image> -->
						</template>
					</uv-input>
					
					
				</uv-form-item>


			</uv-form>
			<uv-button type="primary" text="登陆" customStyle="margin-top: 20px" @click="formLogin()"></uv-button>
			<uv-code ref="uCode" seconds="20" @start="getCodeBtnDisabled = true" @end="getCodeBtnDisabled = false"
				@change="codeChange"></uv-code>
			<!-- #endif -->

			<!--#ifdef MP -->
			<view class="css-flex-x css-justify-center css-align-center css-margin-top-lg">
				<view>
					<uv-checkbox-group @change="agreementChange" shape='square'>
						<uv-checkbox name="1" :checked="agreement"></uv-checkbox>
					</uv-checkbox-group>
				</view>
				<view>
					<view class="css-flex-x css-justify-between css-align-center">
						<text class="css-text-df">我已阅读并同意平台</text>
						<text class="css-text-df css-text-blue"
							@tap="dumpPage('pages/regulations/index',{type:'xhFwcl'})">用户协议</text>
						<text class="css-text-df">和</text>
						<text class="css-text-df css-text-blue"
							@tap="dumpPage('pages/regulations/index',{type:'xhYxzc'})">隐私政策</text>
					</view>
				</view>

			</view>
			<!-- #endif -->
		</view>

		<uv-overlay :show="showOverlay" @click="showOverlay = false"></uv-overlay>
	</view>
</template>
<script>
	import {
		setToken
	} from '@/common/auth';
	export default {
		computed: {},
		data() {
			return {
				getCodeBtnDisabled: false,
				getCodeBtnTips: '',
				loginForm: {
					username: "",
					userpass:'',
					captcha: "",
					captchaUuid: "",
					invitId:'',
				},
				loginRules: {
					username: [{
						required: true,
						trigger: "blur",
						message: "请输入您的手机号码或用户名称"
					}],
					userpass: [{
						required: true,
						trigger: "blur",
						message: "请输入您的密码"
					}],
					reuserpass:[{
						required: true,
						trigger: "blur",
						message: "请再次输入您的密码"
					}],
					captcha: [{
						required: true,
						trigger: "blur",
						message: "请输入您的验证码"
					}]
				},
				codeUrl: '',
				logo: '', //logo的网络地址
				slogan: '', //口语
				showOverlay: false,
				spid: 0,
				agreement: false,
				loading: false, //点了按钮时的加载显示
				code: '',
				imgPic:'',
			};
		},
		methods: {
			isEmpty(item) {
				return uni.$my.isEmpty(item);
			},
			dumpPage(page, params, type) {
				uni.$my.dumpPage(page, params, type)
			},
			agreementChange(e) {
				// console.log(e)
				this.agreement = !this.agreement;
			},
			codeChange(text) {
				this.getCodeBtnTips = text;
			},
			getCode() {
				if (uni.$my.isEmpty(this.loginForm.mobile) || !uni.$uv.test.mobile(this.loginForm.mobile)) {
					uni.$uv.toast('请正确填写手机号码');
					return;
				}
				if (this.$refs.uCode.canGetCode) {
					// 模拟向后端请求验证码
					uni.showLoading({
						title: '正在获取验证码'
					})
					this.loginForm.captchaUuid = ''
					uni.$uv.http.post('/loginSend', this.loginForm).then(res => {
						setTimeout(() => {
							uni.hideLoading();
							// 这里此提示会被this.start()方法中的提示覆盖
							uni.$uv.toast(res.msg);
							if (res.code === 200) {
								this.loginForm.captchaUuid = res.data.captchaUuid || ''
							}
							// 通知验证码组件内部开始倒计时
							// this.$refs.uCode.start();
						}, 2000);
					}).catch(e => {
						console.log(e)
					})
				} else {
					uni.$uv.toast('倒计时结束后再发送');
				}
			},
			getImgCode(){
				// if (uni.$my.isEmpty(this.loginForm.mobile)) {
				// 	uni.$uv.toast('请正确填写用户信息');
				// 	return;
				// }
				// if (uni.$my.isEmpty(this.loginForm.passwd)) {
				// 	uni.$uv.toast('请正确填写密码');
				// 	return;
				// }
				uni.showLoading({
					title: '正在获取验证码'
				})
				this.loginForm.captchaUuid = ''
				uni.$uv.http.post('/captchaImage', this.loginForm).then(res => {
					setTimeout(() => {
						uni.hideLoading();
						// 这里此提示会被this.start()方法中的提示覆盖
						// uni.$uv.toast(res.msg);
						if (res.code === 200) {
							this.loginForm.captchaUuid = res.data.captchaUuid || '';
							this.imgPic = uni.$my.serverHost+'/'+res.data.captchaUrl;
							// console.log(this.imgPic,33333333);
						}else {
							uni.$uv.toast(res.msg);
						}
						// 通知验证码组件内部开始倒计时
						// this.$refs.uCode.start();
					}, 2000);
				}).catch(e => {
					console.log(e)
				})
			},
			formLogin() {
				this.$refs.loginForm.validate().then(res => {
					uni.$uv.http.post('/registerH5', this.loginForm).then(res => {
						if (res.code === 200) {
							this.loginSuccessStorage(res.data)
							// 跳转到来源页
							uni.$uv.toast('注册成功')
							this.backPage();
						} else {
							uni.$uv.toast(res.msg)
						}
					}).catch(e => {
						console.log(e)
					})
				}).catch(errors => {
					uni.$uv.toast('校验失败')
				})

			},
			//登陆成功返回原来的页
			backPage() {
				//再次跳转到指定页,_login_back_page在request.js里缓存
				// let npage = uni.getStorageSync('_login_back_page');
				let npage = '/pages/home/index';
				if (npage.indexOf('/home/') !== -1) {
					getApp().globalData.reInit = true;
					// 跳转到 tabBar 页面，并关闭其他所有非 tabBar 页面。
					uni.switchTab({
						url: npage,
						success: () => {
							uni.removeStorage({
								key: '_login_back_page',
								success: function(res) {
									console.log('success');
								}
							});
						}
					});
				} else {
					// 关闭当前页面，跳转到应用内的某个页面。
					uni.redirectTo({
						url: npage,
						success: () => {
							uni.removeStorage({
								key: '_login_back_page',
								success: function(res) {
									console.log('success');
								}
							});
						}
					});
				}

			},
			//登陆成功后要保存的数据
			loginSuccessStorage(user) {
				setToken(user.token)
				//标识已经登陆
				getApp().globalData.hasLogin = true;
				//保存uid
				uni.setStorage({
					key: 'uuu',
					data: user.id
				});
				//保存分享时使用的推广id
				uni.setStorage({
					key: 'spid',
					data: user.id
				});
			},
			loginError() {
				this.showOverlay = false;
				uni.showToast({
					icon: "none",
					title: '请使用微信授权登陆',
					duration: 3000
				});
			},
			loginSuccessHandle(uid, spid) {
				this.showOverlay = false;
				this.loading = false;
				this.loginSuccessStorage(uid, spid);
				this.backPage();
			},
			//pc端通过微信开放平台扫码登陆
			pcLogin() {
				let host = uni.$my.selfHost();
				uni.$u.http.get('Login/pcLogin', {
					params: {
						token: false,
						scan: 1,
						host: host
					}
				}).then(res => {
					if (Object.prototype.hasOwnProperty.call(res, 'success')) {
						//指定显示容器id
						res.success.id = 'weixin-open-web-scan-box';
						//显示二维码
						// console.log(res.success);
						setTimeout(function() {
							new WxLogin(res.success);
						}, 200);
					}
				}).catch(error => {
					console.log(error);
				});
			},
			//公众号授权登陆
			officialLogin() {
				if (!uni.$my.isWeiXin()) {
					return false;
				}
				let host = uni.$my.selfHost();
				//这里为了与服务端统计接收用get
				uni.$u.http.get('Login/officialLogin', {
					params: {
						token: false,
						host: host,
						type: 1
					}
				}).then(res => {
					if (Object.prototype.hasOwnProperty.call(res, 'success')) {
						window.location.href = res.success;
					}
				});
			},
			//公众号授权登陆成功后的处理
			officialLoginOk(obj) {
				this.loginSuccessStorage(obj.uuu, obj.spid);
				//由于是服务器跳转过来的所以还要处理token
				uni.$my.setToken(obj.token);
				this.backPage();
			},
			//微信授权登陆,可以用于app或小程序登陆
			weixinOauthLogin() {
				if (!this.agreement) {
					uni.showToast({
						icon: "none",
						title: '登陆需要同意用户协议',
						duration: 2000
					});
					return;
				}
				this.showOverlay = true;
				uni.getProvider({
					service: 'oauth',
					success: (res) => {
						//["univerify","weixin","qq","sinaweibo","google","facebook"] 
						// console.log(res.provider);
						if (~res.provider.indexOf('weixin')) {
							uni.login({
								provider: 'weixin',
								onlyAuthorize: true, //必须false,不要code,要access_token
								success: (loginRes) => {
									if (loginRes.errMsg != 'login:ok') {
										this.loginError();
										return false;
									}
									// console.log(loginRes)
									//使用access_token,openid提交给后台查找会员信息登陆
									let url = '/loginMini';
									let params = {
										'code': loginRes.code
									};
									// #ifdef APP-PLUS || APP-NVUE
									url = '/loginApp';
									// #endif
									//推广人
									params.spid = this.spid;
									// console.log(url, params)
									uni.$uv.http.post(url, params).then(res => {
										// console.log(res)
										this.showOverlay = false;
										this.loading = false;
										//登陆成功
										if (res.code === 200) {
											this.loginSuccessStorage(res.data)
											// 跳转到来源页
											uni.$uv.toast('登陆成功')
											this.backPage();
										} else {
											uni.$uv.toast(res.msg)
										}
									}).catch(error => {
										//登陆异常
										console.log(error)
										this.loginError();
									});
								},
								fail: (e) => {
									uni.showToast({
										icon: "error",
										title: '失败',
										duration: 2000
									});
									// console.log('error',e);
								}
							});
						}
					}
				});
			},
			init() {
				// #ifdef H5
				this.agreement = true;
				if (uni.$my.isWeiXin()) {
					//公众号里是使用静默授权登陆
					this.officialLogin();

					return;
				}
				//使用微信开放平台扫码登陆
				// this.pcLogin();
				// #endif
				// 微信小程序自动登陆
				// #ifdef MP
				this.agreement = true;
				this.weixinOauthLogin();
				return;
				// #endif
				//app要点协议同意
				// // #ifdef APP-PLUS
				// this.weixinOauthLogin();
				// // #endif
			},
			openPage(url) {
				uni.navigateTo({
					url: url
				});
			}
		},
		onReady() {

		},
		onLoad(options) {
			options = options || {};
			console.log(options,33333333);
			if (options.spid) {
				this.spid = options.spid;
			} else {
				this.spid = uni.$my.getSpid();
			}
			if(options.invitId){
				this.loginForm.invitId = options.invitId;
			}
			if(!options.invitId){
				uni.showToast({
					icon: "none",
					title: '是否确认没有邀请人',
					duration: 2000
				});
			}
			//公众号或pc扫码登陆后由服务器跳转回来的判断
			// #ifdef H5
			// if (options.login == 1) {
			// 	return this.officialLoginOk(options);
			// } else if (options.login == -1) {
			// 	uni.showToast({
			// 		icon: "none",
			// 		title: '账号已注销,不能登陆',
			// 		duration: 2000
			// 	});
			// }
			// #endif
			this.getImgCode();
			this.init();
			
		}
	};
</script>
<style lang="scss" scoped>
	.page-bg {
		background-color: #d8f1ff;
		background-size: cover;
		/* #ifdef H5 || MP */
		background-image: url('http://card.qqinfor.com/static/img/login-background.c754f204.png');
		/* #endif */
	}
</style>